package stack;

import java.util.EmptyStackException;

public class MyLinkedStack<T> implements MyStack<T> {

    private Node<T> top;

    public MyLinkedStack() {
        top = new Node<>();
    }

    @Override
    public void push(T e) {
        top = new Node<>(e, top);
    }

    @Override
    public T pop() {
        if (isEmpty()) {
            throw new EmptyStackException();
        }
        T item = top.item;
        top = top.next;
        return item;
    }

    @Override
    public T peek() {
        if (isEmpty()) {
            throw new EmptyStackException();
        }
        return top.item;
    }

    @Override
    public boolean isEmpty() {
        return top.end();
    }

    private static class Node<U> {
        private final U item; //the current data
        private final Node<U> next; //the ref to next

        Node() {
            this.item = null;
            this.next = null;
        }

        Node(U item, Node<U> next) {
            this.item = item;
            this.next = next;
        }

        boolean end() {
            return item == null && next == null;
        }

        @Override
        public String toString() {
            return "Node{" +
                    "item=" + item +
                    ", next=" + next +
                    '}';
        }
    }

    @Override
    public String toString() {
        return "MyLinkedStack{" +
                "top=" + top +
                '}';
    }
}
